//
//  NumberFieldView.m
//  quickBatchManager
//
//  Created by 王定波 on 15/10/19.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "NumberFieldView.h"

@implementation NumberFieldView
{
    UIButton *singelBtn;
    UIButton *mulBtn;
    UIView *maintableView;
    NSMutableDictionary *selectNumber;
    UILabel *totalLabel;
    
}

@synthesize selectNumber;

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

-(instancetype)initWithFrame:(CGRect)frame
{
    if(self=[super initWithFrame:frame])
    {
        [self initUI];
    }
    return self;
}


-(instancetype)init
{
    if(self=[super init])
    {
        [self initUI];
    }
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if(self=[super initWithCoder:aDecoder])
    {
        [self initUI];
    }
    return self;
}

-(void) initUI
{
    singelBtn=[[UIButton alloc] init];
    [singelBtn setTitle:@"单选" forState:UIControlStateNormal];
    
    [singelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [singelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    singelBtn.translatesAutoresizingMaskIntoConstraints = NO;
    
    [singelBtn setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.89 green:0.86 blue:0.84 alpha:1]] forState:UIControlStateNormal];
    [singelBtn setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.06 green:0.64 blue:0.78 alpha:1]] forState:UIControlStateSelected];
    [singelBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [self addSubview:singelBtn];
    
    
    
    
    mulBtn=[[UIButton alloc] init];
    [mulBtn setTitle:@"多选" forState:UIControlStateNormal];
    
    [mulBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [mulBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [mulBtn setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.89 green:0.86 blue:0.84 alpha:1]] forState:UIControlStateNormal];
    [mulBtn setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.06 green:0.64 blue:0.78 alpha:1]] forState:UIControlStateSelected];
    mulBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [mulBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [self addSubview:mulBtn];
    
    [singelBtn bk_whenTapped:^{
        singelBtn.selected=YES;
        mulBtn.selected=NO;
        
        for (NSString *key in selectNumber) {
            NumberFieldModel *number=[selectNumber objectForKey:key];
            number.numberField.backgroundColor=[UIColor whiteColor];
            number.isSelect=NO;
        }
        
    }];
    
    [mulBtn bk_whenTapped:^{
        singelBtn.selected=NO;
        mulBtn.selected=YES;
    }];
    
    singelBtn.selected=YES;
    
    maintableView=[[UIView alloc] init];
    maintableView.translatesAutoresizingMaskIntoConstraints = NO;
    maintableView.backgroundColor=[UIColor colorWithRed:0.73 green:0.72 blue:0.69 alpha:1];
    [self addSubview:maintableView];
    
    
    
    totalLabel=[[UILabel alloc] init];
    totalLabel.backgroundColor=[UIColor whiteColor];
    
    totalLabel.textAlignment=NSTextAlignmentLeft;
    totalLabel.font=[UIFont systemFontOfSize:16];
    totalLabel.translatesAutoresizingMaskIntoConstraints = NO;
    totalLabel.textColor=[UIColor colorWithRed:0.50 green:0.49 blue:0.46 alpha:1];
    totalLabel.text=[NSString stringWithFormat:@"    共计：%d件",0];
    [maintableView addSubview:totalLabel];
    
    
    //布局
    [self setEdge:self firstView:singelBtn secondView:self attr:NSLayoutAttributeLeft constant:0];
    [self setEdge:self firstView:singelBtn secondView:self attr:NSLayoutAttributeTop constant:0];
    [self setEdge:singelBtn firstView:singelBtn secondView:nil attr:NSLayoutAttributeHeight constant:40];
    [self setEdge:singelBtn firstView:singelBtn secondView:nil attr:NSLayoutAttributeWidth constant:110];
    
    [self setEdge:self firstView:mulBtn secondView:singelBtn attr:NSLayoutAttributeHeight constant:0];
    [self setEdge:self firstView:mulBtn secondView:singelBtn attr:NSLayoutAttributeWidth constant:0];
    [self setEdge:self firstView:singelBtn secondView:mulBtn attr:NSLayoutAttributeCenterY constant:0];
    
    [self addConstraint:[NSLayoutConstraint constraintWithItem:singelBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:mulBtn attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]];
    
    
    
    [self addConstraint:[NSLayoutConstraint constraintWithItem:singelBtn attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:maintableView attribute:NSLayoutAttributeTop multiplier:1.0 constant:-5]];
    [self setEdge:self firstView:maintableView secondView:self attr:NSLayoutAttributeLeft constant:0];
    [self setEdge:self firstView:maintableView secondView:self attr:NSLayoutAttributeRight constant:0];
    [self setEdge:self firstView:maintableView secondView:self attr:NSLayoutAttributeBottom constant:0];
    
    
    
    
    [self setEdge:totalLabel firstView:totalLabel secondView:nil attr:NSLayoutAttributeHeight constant:35];
    [self setEdge:maintableView firstView:totalLabel secondView:maintableView attr:NSLayoutAttributeLeft constant:1];
    [self setEdge:maintableView firstView:totalLabel secondView:maintableView attr:NSLayoutAttributeRight constant:-1];
    [self setEdge:maintableView firstView:totalLabel secondView:maintableView attr:NSLayoutAttributeBottom constant:-1];
    
    
    [self reloadTableView];
    
}


-(void)setSizeList:(NSArray *)sizeList
{
    _sizeList=sizeList;
    [self reloadTableView];
    
}

-(void)setColorList:(NSArray *)colorList
{
    _colorList=colorList;
    [self reloadTableView];
}


-(void)reloadTableView
{
    for (UIView *view in maintableView.subviews) {
        if(![view isEqual:totalLabel])
        {
            [view removeFromSuperview];
        }
    }
    [selectNumber removeAllObjects];
    
    
    
    if(_sizeList.count>0 && _colorList.count>0)
    {
        
        selectNumber=[[NSMutableDictionary alloc] init];
        
        for (int i=1; i<=_colorList.count; i++) {
            for (int j=1; j<=_sizeList.count; j++) {
                int tag=i*100+j+1;
                NumberFieldModel *number=[[NumberFieldModel alloc] init];
                number.isSelect=NO;
                number.number=0;
                [selectNumber setObject:number forKey:[NSString stringWithFormat:@"%d",tag]];
            }
        }
        
        
        
        for (UIView *view in self.subviews) {
            [view setHidden:NO];
        }
        
        for (int i=0; i<_colorList.count+1; i++) {
            for (int j=0; j<_sizeList.count+1; j++) {
                
                UIView *tab;
                int tag=i*100+j+1;
                NSString *key=[NSString stringWithFormat:@"%d",tag];
                
                
                if(i==0 || j==0)
                {
                    UILabel *title=[[UILabel alloc] init];
                    title.translatesAutoresizingMaskIntoConstraints = NO;
                    
                    if(i==0)
                        title.backgroundColor=[UIColor colorWithRed:0.97 green:0.96 blue:0.93 alpha:1];
                    else title.backgroundColor=[UIColor whiteColor];
                    
                    title.textAlignment=NSTextAlignmentCenter;
                    title.font=[UIFont systemFontOfSize:16];
                    title.textColor=[UIColor colorWithRed:0.50 green:0.49 blue:0.46 alpha:1];
                    
                    
                    if(i==0 && j==0)
                        title.text=@"颜色";
                    else if(j==0)
                    {
                        title.text=_colorList[i-1];
                    }
                    else if(i==0)
                    {
                        title.text=_sizeList[j-1];
                    }
                    [maintableView addSubview:title];
                    tab=title;
                }
                else
                {
                    
                    NumberFieldModel *number=[selectNumber objectForKey:key];
                    UITextField *numberField=[[UITextField alloc] init];
                    numberField.backgroundColor=[UIColor whiteColor];
                    numberField.textAlignment=NSTextAlignmentCenter;
                    numberField.translatesAutoresizingMaskIntoConstraints = NO;
                    
                    numberField.font=[UIFont systemFontOfSize:16];
                    numberField.textColor=[UIColor colorWithRed:0.50 green:0.49 blue:0.46 alpha:1];
                    numberField.keyboardType=UIKeyboardTypeNumberPad;
                    number.numberField=numberField;
                    [numberField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
                    
                    
                    
                    UIView *view=[[UIView alloc] initWithFrame:numberField.frame];
                    view.userInteractionEnabled=YES;
                    view.translatesAutoresizingMaskIntoConstraints = NO;
                    
                    [view bk_whenTapped:^{
                        
                        if(mulBtn.selected)
                        {
                            number.isSelect=!number.isSelect;
                            if(!number.isSelect)
                            {
                                numberField.backgroundColor=[UIColor whiteColor];
                                [numberField resignFirstResponder];
                            }
                            else {
                                numberField.backgroundColor=[UIColor colorWithWhite:0.95 alpha:1];
                                [numberField becomeFirstResponder];
                            }
                            
                        }
                        else
                        {
                            [numberField becomeFirstResponder];
                        }
                        
                    }];
                    
                    
                    [maintableView addSubview:numberField];
                    [maintableView addSubview:view];
                    [self setEdge:maintableView firstView:numberField secondView:view attr:NSLayoutAttributeTop constant:0];
                    [self setEdge:maintableView firstView:numberField secondView:view attr:NSLayoutAttributeBottom constant:0];
                    [self setEdge:maintableView firstView:numberField secondView:view attr:NSLayoutAttributeLeft constant:0];
                    [self setEdge:maintableView firstView:numberField secondView:view attr:NSLayoutAttributeRight constant:0];
                    
                    tab=numberField;
                }
                
                
                
                
                //布局
                tab.tag=tag;
                [self setEdge:self firstView:tab secondView:totalLabel attr:NSLayoutAttributeHeight constant:0];
                if(i==0)
                {
                    [self setEdge:maintableView firstView:tab secondView:maintableView attr:NSLayoutAttributeTop constant:1];
                }
                else
                {
                    [maintableView addConstraint:[NSLayoutConstraint constraintWithItem:[maintableView viewWithTag:(i-1)*100+j+1] attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tab attribute:NSLayoutAttributeTop multiplier:1.0 constant:-1]];
                }
                
                
                
                if(j==0)
                {
                    [self setEdge:maintableView firstView:tab secondView:maintableView attr:NSLayoutAttributeLeft constant:1];
                }
                else
                {
                    [maintableView addConstraint:[NSLayoutConstraint constraintWithItem:[maintableView viewWithTag:i*100+(j-1)+1] attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:tab attribute:NSLayoutAttributeLeft multiplier:1.0 constant:-1]];
                }
                
                
                if(i!=0 || j!=0)
                {
                    
                    [self setEdge:self firstView:tab secondView:[maintableView viewWithTag:1] attr:NSLayoutAttributeWidth constant:0];
                }
                
                
                if(i==_colorList.count)
                {
                    [maintableView addConstraint:[NSLayoutConstraint constraintWithItem:tab attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:totalLabel attribute:NSLayoutAttributeTop multiplier:1.0 constant:-1]];
                    
                }
                
                if(j==_sizeList.count)
                {
                    [self setEdge:maintableView firstView:tab secondView:maintableView attr:NSLayoutAttributeRight constant:-1];
                }
                
                
            }
        }
        
        [self reloadData];
    }
    else
    {
        for (UIView *view in self.subviews) {
            [view setHidden:YES];
        }
    }
}


//自动布局快速添加
- (void)setEdge:(UIView*)supperView firstView:(UIView*)firstView secondView:(UIView*)secondView attr:(NSLayoutAttribute)attr constant:(CGFloat)constant
{
    if(secondView==nil)
        [supperView addConstraint:[NSLayoutConstraint constraintWithItem:firstView attribute:attr relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:constant]];
    else [supperView addConstraint:[NSLayoutConstraint constraintWithItem:firstView attribute:attr relatedBy:NSLayoutRelationEqual toItem:secondView attribute:attr multiplier:1.0 constant:constant]];
}

-(void)textFieldChanged:(id)sender
{
    UITextField *text=(UITextField*)sender;
    double total=0;
    for (NSString *key in selectNumber) {
        NumberFieldModel *number=[selectNumber objectForKey:key];
        if(number.isSelect && mulBtn.isSelected)
        {
            number.numberField.text=text.text;
        }
        
        total+=[number.numberField.text intValue];
    }
    
    totalLabel.text=[NSString stringWithFormat:@"    共计：%.0f件",total];
}


-(void)reloadTotal
{
    double total=0;
    for (NSString *key in selectNumber) {
        NumberFieldModel *number=[selectNumber objectForKey:key];
        total+=[number.numberField.text intValue];
    }
    
    totalLabel.text=[NSString stringWithFormat:@"    共计：%.0f件",total];
}

-(BOOL)checkInput:(BOOL) isAll
{
    for (NSString *key in selectNumber) {
        NumberFieldModel *number=[selectNumber objectForKey:key];
        if([number.numberField.text isBlank] && isAll)
        {
            return NO;
        }
        else if(!isAll)
        {
            if(![number.numberField.text isBlank])
            {
                return YES;
            }
        }
    }
    
    return isAll;
}


-(void)setDataList:(NSArray *)dataList
{
    _dataList=dataList;
    [self reloadData];
}

-(void)reloadData
{
    if(_dataList)
    {
        int i=0;
        for (NSArray *row in _dataList) {
            int j=0;
            for (NSString *num in row) {
                int tag=(i+1)*100+(j+1)+1;
                UITextField *numField=(UITextField*)[maintableView viewWithTag:tag];
                if(numField)
                {
                    numField.text=num;
                }
                
                j++;
            }
            i++;
        }
        [self reloadTotal];
    }
}

@end
